<?php
class Image extends Object
{
	public $name;
	public $path;
	public $file;
	public $width;
	public $height;
	public $type;
	public $info;

	public function Image($file)
	{
        $this->file = $file;
		$this->name = basename($file);
		$this->path = FileHandler::GetPath($file);
		if ($this->IsValid())
		{
			$this->width = $this->info[0];
			$this->height = $this->info[1];
			$this->type = FileHandler::GetExt($this->info['mime']);
		}
	}

	public function IsValid()
	{
		$supported = array ('gif','jpg','png','jpeg');
		$this->type = FileHandler::GetExt($this->name);
        try
		{
            if (!in_array($this->type, $supported)) throw new Exception("File {$this->name} not supported");
            else if (!file_exists($this->file)) throw new Exception("File {$this->file} not existed");
	        $this->info = getimagesize($this->file);
            return true;
		}
		catch (Exception $ex)
		{
			return false;
		}
	}

	public function Resize($w, $h, $rs_path, $keep_aspect = true)
	{
		$rs_file = $rs_path.DS.$this->name;
        if ($w > $this->width && $h > $this->height)
        {
            copy($this->file, $rs_file);
        }
        else
        {
            if ($keep_aspect) $resized_w = (int)($h * $this->width / $this->height);
            if ($resized_w > $w) $h = (int)($w * $this->height / $this->width);
            else $w = $resized_w;
            try
            {
                $image = $this->CreateImg();
                $output_image = imagecreatetruecolor($w, $h);
                imageinterlace($output_image, true);
                imagealphablending($output_image, false);
                imagesavealpha($output_image, true);
                imagecopyresampled($output_image, $image, 0, 0, 0, 0, $w, $h, $this->width, $this->height);
                $this->OutputImg($output_image, $rs_file);
                imagedestroy($output_image);
            }
            catch (Exception $ex)
            {
                throw new Exception('cant create image');
            }
        }
	}

	private function CreateImg()
	{
		switch ($this->type)
		{
			case 'jpg':
			case 'jpeg':
				$type="jpeg";
				$img = imagecreatefromjpeg($this->file);
				break;
			case 'png':
				$img = imagecreatefrompng($this->file);
				break;
			case 'gif':
				$img = imagecreatefromgif($this->file);
				break;
			default:
				throw new Exception('Not supported file');
				return;
		}
        if (!$img) throw new Exception('Image corrupted');
		return $img;
	}

	private function OutputImg($output_image, $path =null)
	{
		switch ($this->type)
		{
			case 'jpg':
			case 'jpeg':
				imagejpeg($output_image, $path, 100);
				break;
			case 'png':
				imagepng($output_image, $path);
				break;
			case 'gif':
				imagegif($output_image, $path);
				break;
		}
	}
}
?>
